package com.usian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.mapper.AdUserMapper;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.service.AdUserService;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Override
    public ResponseResult login(AdUserDto dto) {

        /**
         * 1:校验参数
         */
        if(dto==null ||(StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2:根据用户名去aduser表中查询有效用户 查出来aduser对象
        QueryWrapper<AdUser> queryWrapper =new QueryWrapper<>();
        queryWrapper.lambda().eq(AdUser::getName,dto.getName());
        AdUser adUser = this.getOne(queryWrapper);
        if(adUser!=null){
            //比较密码  当前用户输入密码串+数据库查出来的salt 拼接  生成新的md5密码串 ，比较新密码串和数据库中的密码串  一致 对  反之
            String psw =dto.getPassword()+ adUser.getSalt();
            String newPwd = DigestUtils.md5DigestAsHex(psw.getBytes()); //md5密码串

            if(adUser.getPassword().equals(newPwd)){
                //比较成功，生成token给前端(token,user)
                Map<String,Object> map =new HashMap<>();
                adUser.setPassword("");
                adUser.setSalt("");
                map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
                map.put("user",adUser);
                return ResponseResult.okResult(map);
            }else{
                //失败
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
    }
}
